//axios请求接口封装
import axios from "axios";

// 创建axios实例 
const request = axios.create({
    baseURL: "/api",
    timeout: 5000,
    // headers: {
    //     "Content-Type": "application/json",
    // },
});

// 请求拦截器
request.interceptors.request.use(
    config => {
        // 从localStorage获取token
        const token = localStorage.getItem('token')
        if (token) {
            config.headers.Authorization = token
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 添加响应拦截器
request.interceptors.response.use(
    response => {
        // 直接返回完整的 response，让组件自己处理数据结构
        return response
    },
    error => {
        if (error.response?.status === 401) {
            // token过期，清除token并跳转到登录页
            localStorage.removeItem('token')
            window.location.href = '/login'
        }
        return Promise.reject(error)
    }
)

export default request;

